/* @Post 装饰器 */
import { Application, Request } from 'express'
const http = require('http');
const WebSocket = require('ws')
export const Post = (path: string) => {
  return (target: any, key: string, descriptor: TypedPropertyDescriptor<any>) => {
    const timer = setTimeout(() => {
      const app = global.appGlobal
      const pool = global.poolGlobal
      let parPath = ''
      if ('parPath' in target) {
        parPath = target.parPath
      }
      path = `${parPath}${path}`
      app.post(path, function (req, res) {
        target[key]({
          req: req,
          res: res
        }, pool)
      })
      clearTimeout(timer)
    }, 0)
  }
}

/* @Parpath 装饰器，用于定义父级路径 */
export const Parpath = (path: string) => {
  return (target: any) => {
    target.prototype.parPath = path
  }
}

/* ws装饰器 */
export const Ws = (path: string, port: number) => {
  return (target: any, key: string, descriptor: TypedPropertyDescriptor<any>) => {
    const timer = setTimeout(() => {
      let parPath = ''
      if ('parPath' in target) {
        parPath = target.parPath
      }
      path = `${parPath}${path}`
      const ws = new (WebSocket as any).Server({ port: port, path: path  })
      ws.on('connection', (socket: any) => {
        target[key]({socket, ws})
      })
      clearTimeout(timer)
    }, 0)
  }
}
